package com.juli.aimanager.system.controller;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.juli.aimanager.base.BaseController;
import com.juli.aimanager.common.Tree;
import com.juli.aimanager.system.dto.MenuDO;
import com.juli.aimanager.system.dto.SysUserDO;
import com.juli.aimanager.system.service.LoginService;
import com.juli.aimanager.system.service.MenuService;
@Controller
@RequestMapping(value="/login")
public class LoginController extends BaseController{
	private final Logger logger = LoggerFactory.getLogger(this.getClass());
	@Autowired
	private LoginService loginService;
	@Autowired
	MenuService menuService;
	@RequestMapping(value="/index")
	public String index(Model model) throws Exception {
		SysUserDO user = (SysUserDO) session.getAttribute("user");
		Tree<MenuDO> menuTree = menuService.getSysMenuTree(user.getUserId());
		model.addAttribute("menus", menuTree);
		model.addAttribute("name",user.getUsername());
		logger.info(user.getName());
		return "/jsp/index";
	}
	@SuppressWarnings({ "unchecked", "unused", "rawtypes" })
	@RequestMapping(value="/login")
	@ResponseBody
	public Map<String, String> login(HttpServletRequest request, @RequestParam Map<String, String> paramsMap){
		Map<String, String> messageMap = new HashMap();
		Map<String,Object> sessionMap = new HashMap<String,Object>();
		try {
			List list=loginService.loginChecked(paramsMap);
			if(list.size()==0){
				messageMap.put("oper", "f");
				messageMap.put("msg", "不存在该用户！");
				return messageMap;
			}else{
				Map map=(Map) list.get(0);
				String pwd=map.get("PASSWORD").toString();
				if(pwd.equals(paramsMap.get("password").toString())){
					messageMap.put("oper", "s");
					HttpSession session = request.getSession();
					session.setAttribute("userId", map.get("ID").toString());
					session.setAttribute("password", pwd);
					session.setAttribute("username", map.get("USERNAME").toString());
					SysUserDO user = new SysUserDO();
					user.setUsername(map.get("USERNAME").toString());
					user.setUserId((Long) map.get("ID"));
					session.setAttribute("user", user);
					return messageMap;
				}else{
					messageMap.put("oper", "f");
					messageMap.put("msg", "密码不正确！");
					return messageMap;
				}
				
			}
		} catch (Exception e) {
			logger.error("登录出错了。"+e.getMessage());
		}
		return messageMap;
	}
}
